<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\func\Lib;
use app\common\func\Tools;
use app\common\model\Company;
use app\common\model\EquipFigure;
use app\common\model\transaction\Xyf;
use app\common\model\User;
use app\common\model\UserCard;
use EasyWeChat\Factory;
use fast\Random;
use fast\Rsa;
use think\Config;
use think\Db;
use think\Env;
use think\Exception;

/**
 * 手机短信接口
 */
class V1 extends Api
{
    protected $noNeedLogin = ['getReferrer', "test", "getProductList", "sendSms", "getBalanceType", "getAgree", "test1"];
    protected $noNeedRight = '*';
    protected $typeArr = [0, 1, 2]; //上级类型：1=机构，2=代理

    public function getEquipManage()
    {
        $list = Lib::getEquipManage(2, $this->auth->id);

        $this->success("设备管理", $list);
    }

    public function getEquipCountList()
    {
        $productId = $this->request->post('product_id');
        $startTime = $this->request->post('start_time');
        $endTime = $this->request->post('end_time');
        $page = $this->request->post('page', "1");
        $pageSize = $this->request->post('page_size', "15");

        if (!$productId || !$startTime || !$endTime) {
            $this->error("缺少参数!");
        }

        $startTime = strtotime($startTime);
        $endTime = strtotime("+1 day", strtotime($endTime));

        $list = Lib::getEquipCountList(2, $this->auth->id, $productId, $startTime, $endTime, $page, $pageSize);

        $this->success("设备列表", $list);
    }

    public function getEquipCount()
    {
        $startTime = $this->request->post('start_time');
        $endTime = $this->request->post('end_time');

        if (!$startTime || !$endTime) {
            $time = date("Y-m");
            $startTime = strtotime($time);
            $endTime = strtotime("+1 month", strtotime($time));
        } else {
            $startTime = strtotime($startTime);
            $endTime = strtotime("+1 day", strtotime($endTime));
        }

        $list = Lib::getEquipCount(2, $this->auth->id, $startTime, $endTime);

        $this->success("激活设备统计", ["data" => $list, "time" => ["start" => $startTime, "end" => $endTime - 1]]);
    }

    public function getMoneyDetails()
    {
        $balanceTypeId = $this->request->post('balance_type');
        $pageSize = $this->request->post('page_size', 15);

        if (!$balanceTypeId) {
            $this->error("缺少余额类型");
        }

        $list = Lib::getMoneyDetails(2, $this->auth->id, $balanceTypeId, $pageSize);

        $this->success("余额明细", $list);
    }

    //账户明细产品卡片
    public function getMoneyCard()
    {
        $startTime = $this->request->post('start_time');
        $endTime = $this->request->post('end_time');
        $balanceTypeId = $this->request->post('balance_type');

        if (!$balanceTypeId) {
            $this->error("缺少余额类型");
        }

        if ($startTime && $endTime) {
            if ($startTime > $endTime) {
                $this->error("请确认查询时间");
            }
            $startTime = strtotime($startTime);
            $endTime = strtotime("+1 day", strtotime($endTime));
        } else {
            $startTime = 0;
            $endTime = 0;
        }

        $list = Lib::getMoneyCard(2, $this->auth->id, $balanceTypeId, $startTime, $endTime);
        $this->success("账户余额-产品分类", $list);
    }

    public function getTranList()
    {
        $type = $this->request->post('type', "month");
        $date = $this->request->post('date');
        $productId = $this->request->post('product_id');
        $pageSize = $this->request->post('page_size',15);

        if (!$productId) {
            $this->error("缺少参数");
        }

        if (!$date) {
            $this->error("缺少查询日期");
        }

        if ($type == "month") {
            $startTime = strtotime($date);
            $endTime = strtotime("+1 month", strtotime($date));
        } elseif ($type == "day") {
            $startTime = strtotime(date("Y-m-d", strtotime($date)));
            $endTime = strtotime("+1 day", strtotime($date));
        } else {
            $this->error("查询类型错误");
        }

        $list = Lib::getTranList(2, $this->auth->id, $productId, $startTime, $endTime,$pageSize);

        $this->success("交易列表", $list);
    }

    public function getTranListCount()
    {
        $type = $this->request->post('type', "month");
        $pageSize = $this->request->post('page_size', "15");

        $list = Lib::getTranCountList(2, $this->auth->id, $type, $pageSize);

        $this->success("交易列表统计", $list);
    }

    //客服电话
    public function getKefu()
    {
//        $phone = '';
//        $user = User::where('id', $this->auth->id)->find();
//        if (!empty($user)) {
//            if ($user->ptype == 2) {
//                $phone = User::where('id', $user->pid)->value('username');
//            } else {
//                $phone = Company::where('id', $user->pid)->value('contact_phone');
//            }
//        }
//        $this->success("客服电话", Config::get("site.kefu"));
        $this->success("客服电话", "请联系上级！");
    }

    //相关协议
    public function getAgree()
    {
        $this->success("相关协议", [
            "about" => Config::get("site.about"),
            "user_agree" => Config::get("site.user_agree"),
            "register" => Config::get("site.register"),
            "contract" => config("contract"),
        ]);
    }

    //未绑定设备列表
    public function getUnbindEquip()
    {
        $productId = $this->request->post('product_id');

        if(!$productId){
            $this->error("缺少产品ID");
        }

        $list = Lib::getUnbindEquip(2, $this->auth->id,$productId);

        $this->success("我的设备", $list);
    }

    //下级列表
    public function getChildList()
    {
        $pageSize = $this->request->post('page_size', 15);

        $list = Lib::getChildUserList(2, $this->auth->id, $pageSize);

        $this->success("下级列表", $list);
    }

    //激活设备列表
    public function getActiveList()
    {
        $pageSize = $this->request->post('page_size', 15);

        $list = Lib::getActiveEquipList(2, $this->auth->id, $pageSize);

        $this->success("激活设备列表", $list);
    }

    //交易详情
    public function getTranDetails()
    {
        $list = Lib::getTranDetails(2, $this->auth->id);

        $this->success("交易详情", $list);
    }

    //保存身份证信息
    public function saveIdCard()
    {
        $front = $this->request->post('front');
        $back = $this->request->post('back');
        $name = $this->request->post('name');
        $idcard = $this->request->post('idcard');

        if (!$front || !$back) {
            $this->error("缺少图片");
        }

        if (!empty($idcard)) {
            $nums = User::where("idcards", $idcard)->where("status", "normal")->count();
            if ($nums > 0) {
                $this->error("该身份证号已被实名！");
            }
        }

        $card = new UserCard();
        $card->sale_id = $this->auth->id;
        $card->card_front = $front;
        $card->card_back = $back;
        $result = $card->save();

        if ($result) {
            $user = $this->auth->getUser();
            $user->is_verify = 1;
            if (!empty($name)) {
                $user->nickname = $name;
            }
            if (!empty($idcard)) {
                $user->idcards = $idcard;
            }
            $user->save();
            $this->success("保存成功！");
        } else {
            $this->error("保存失败！");
        }
    }

    //用户余额列表
    public function getMoneyLog()
    {
        $type = $this->request->post('type');
        $pageSize = $this->request->post('page_size', 15);
        $startTime = $this->request->post('start_time');
        $endTime = $this->request->post('end_time');

        if (!empty($startTime) && !empty($endTime)) {
            $startTime = strtotime($startTime);
            $endTime = strtotime($endTime);
            if ($startTime >= $endTime) {
                $this->error("请确认时间！");
            }
        }

        $list = Lib::getMoneyList(2, $this->auth->id, $type, $pageSize, $startTime, $endTime);
        $list = $list->items();
        foreach ($list as $key => &$val) {
            $product = Lib::getProductBySn($val['sn']);
            $val['order_info'] = $val['order_info'] ? json_decode($val['order_info'], true) : "";
            $val['product_name'] = $product ? $product['name'] : "";
        }
        unset($val);

        $this->success("用户余额列表", $list);
    }

    //用户余额
    public function getBalanceInfo()
    {
        $list = Lib::getUserMoney(2, $this->auth->id);

        $this->success("用户余额", $list);
    }

    //团队列表
    public function getMyTeamList()
    {
        $pageSize = $this->request->post('page_size', 15);

        $list = Lib::getChildUserList(2, $this->auth->id, $pageSize);

        $this->success("下级列表", $list);
    }

    //团队列表
    public function getMyTeamListNew()
    {
        $pageSize = $this->request->post('page_size', 15);

        $list = Lib::getChildUserList(2, $this->auth->id, $pageSize);

        $data = $list->items();

        foreach($data as $val) {
            $teamNums = Lib::getTeamAllUser($val->id, 2);
            $val["team_nums"] = count($teamNums);
        }

        $this->success("下级列表", $data);
    }

    //团队统计
    public function getMyTeamInfo()
    {
        $now = time();
        $month = strtotime(date("Y-m", $now));
        $lastMonth = strtotime(date("Y-m", strtotime("-1 month")));

        $total = Lib::getChildUsers(2, $this->auth->id);
        $monthTotal = Lib::getChildUsers(2, $this->auth->id, $month, $now);
        $lastTotal = Lib::getChildUsers(2, $this->auth->id, $lastMonth, $month - 1);

        $this->success("团队信息", ["total" => count($total), "month" => count($monthTotal), "last_month" => count($lastTotal)]);
    }

    //交易列表
    public function getDataList()
    {
        $pageSize = $this->request->post('page_size', 15);

        $list = Lib::getTranDataList(2, $this->auth->id, $pageSize);

        $this->success("交易列表", $list);
    }

    //数据页信息
    public function getData()
    {
        $now = time();
        $month = strtotime(date("Y-m", $now));

        $tran = Lib::getTranData(2, $this->auth->id, $month, $now);
        $active = Lib::getUserActiveEquip(2, $this->auth->id, $month, $now);
        $child = Lib::getChildUsers(2, $this->auth->id, $month, $now);
        $childAll = Lib::getChildUsers(2, $this->auth->id);

        $this->success("数据页", [
            "tran" => $tran,
            "active" => [
                "month" => $active,
                "total" => Lib::getUserActiveEquip(2, $this->auth->id)
            ],
            "child" => [
                "month" => count($child),
                "total" => count($childAll)
            ],
        ]);
    }

    //月收入统计
    public function getIncome()
    {
        $type = $this->request->post('type');

        $list = Lib::getMonthIncome(2, $this->auth->id, 1, $type);

        $this->success("月收入统计", $list);
    }

    //设备详情
    public function getEquipInfo()
    {
        $id = $this->request->post('id');

        if (!$id) {
            $this->error("缺少参数！");
        }

        $info = Lib::getEquipInfo($id);

        if (!$info) {
            $this->error("未找到设备信息！");
        }

        $main = Tools::getMainInfoApi($info['main_type'], $info['main_id']);
        $info["main_info"] = $main['data'];

        $this->success("设备信息", $info);
    }

    //用户设备列表
    public function getEquipList()
    {
        $pageSize = $this->request->post('page_size', 15);
        $sn = $this->request->post('sn', "");
        $status = $this->request->post('status', 0); //状态：0=全部，1=已激活、已绑定，2=未激活，3=未绑定
        $productId = $this->request->post('product_id');

        if (!$productId) {
            $this->error("缺少参数！");
        }

        $list = Lib::getEquipList(2, $this->auth->id, $productId, $pageSize, $sn, $status);
        foreach ($list as $key => $val) {
            $main = Tools::getMainInfoApi($val->main_type, $val->main_id);
            $val->main_info = $main['data'];
            if($val->binding_time == 0){
                $val->standard = [
                    "limit_time" => date("Y-m-d H:i:s",strtotime("+180 day",$val->create_time)),
                    "left" => 180 - ceil((time() - $val->create_time)/(60 * 60 * 24))
                ];
            }
        }

        $this->success("设备列表", $list);
    }

    //首页数据
    public function getIndexData()
    {
        $now = time();
        $todayStart = date("Y-m-d", $now);
        $yesterdayStart = date("Y-m-d", strtotime("-1 day",$now));
        $monthStart = date("Y-m", $now);

        $todayProfit = Lib::getBalanceSum(2, $this->auth->id, strtotime($yesterdayStart), strtotime($todayStart) -1);
        $monthProfit = Lib::getBalanceSum(2, $this->auth->id, strtotime($monthStart), strtotime($todayStart) -1);

        $activeTotal = Lib::getUserActiveEquip(2, $this->auth->id,1,strtotime($todayStart) -1);
        $activeToday = Lib::getUserActiveEquip(2, $this->auth->id, strtotime($yesterdayStart), strtotime($todayStart) -1);
        $activeMonth = Lib::getUserActiveEquip(2, $this->auth->id, strtotime($monthStart), strtotime($todayStart) -1);

        $this->success("数据", [
            "day_profit" => $todayProfit,
            "month_profit" => $monthProfit,
            "active_total" => $activeTotal,
            "active_today" => $activeToday,
            "active_month" => $activeMonth,
        ]);
    }

    //银行卡信息
    public function saveBankInfo()
    {
        $cardType = $this->request->post('card_type');
        $bankName = $this->request->post('bank_name');
        $bankNumber = $this->request->post('bank_number');

        if (!$cardType || !$bankName || !$bankNumber) {
            $this->error("缺少必要信息！");
        }

        $bank = Lib::getBankCard($this->auth->id);

        if (!$bank) {
            $this->error("用户信息不存在！");
        }

        $bank->card_type = $cardType;
        $bank->bank_name = $bankName;
        $bank->bank_card_number = $bankNumber;
        $result = $bank->save();

        if ($result) {
            $this->success("保存成功！");
        } else {
            $this->error("保存失败！");
        }
    }

    //余额类型列表
    public function getBalanceType()
    {
        $list = Lib::getBalanceType();

        $this->success("余额类型列表", $list);
    }

    //余额流水记录
    public function getMoneyLogs()
    {
        $pageSize = $this->request->post('page_size', 15);

        $list = Lib::getMoneyLogs(2, $this->auth->id, $pageSize);
        foreach ($list as $key => $val) {
            $product = Lib::getProductBySn($val->sn);
            $val->order_info = json_decode($val->order_info, true);
            $val->product_name = $product ? $product['name'] : "";
        }

        $this->success("余额日志列表", $list);
    }

    //用户信息
    public function getUserInfo()
    {
        $balanceType = $this->request->post('balance_type', 0);

        $bank = []; //Lib::getUserBank($this->auth->id);
        $balance = Lib::getMoney(2, $this->auth->id, $balanceType);

        $this->success("用户信息", ["bank" => $bank, "balance" => $balance]);
    }

    //发送验证码
    public function sendSms()
    {
        $mobile = $this->request->post('mobile');
        $type = $this->request->post('type', 1);
        if ($type == 3) {
            if ($this->auth->username == $mobile) {
                $this->error("请输入新手机号！");
            } else {
                $nums = Db::name("user")->where(["mobile" => $mobile, "status" => "normal"])->count();
                if ($nums > 0) {
                    $this->error("该手机号已注册！");
                }
            }
        }
        $code = Random::numeric(6);
        $result = sendSms(65, $code, $mobile);
        if ($result == "OK") {
            $this->success("发送成功！");
        } elseif ($result == "Failed") {
            $this->error("发送失败！");
        } elseif ($result == "NO") {
            $this->error("请稍后再试！");
        }
    }

    //注册-产品列表
    public function getProductList()
    {
        $type = $this->request->post('type');
        $id = $this->request->post('id');

        if (!$type || !$id) {
            $this->error("缺少参数!");
        }

        if (!in_array($type, $this->typeArr)) {
            $this->error("上级类型错误!");
        }

        $product = Lib::getMyProduct5($id, $type);

        $this->success("产品列表", $product);
    }

    //注册-推荐人
    public function getReferrer()
    {
        $type = $this->request->post('type');
        $id = $this->request->post('id');

        if (!$type || !$id) {
            $this->error("缺少参数!");
        }

        if (!in_array($type, $this->typeArr)) {
            $this->error("上级类型错误!");
        }

        $info = Tools::getMainInfoApi($type, $id);

        $this->success("推荐人信息", $info);
    }

    public function test()
    {
        $wechat = config("wechat_klyfw");
        $config = [
            'app_id' => $wechat["AppID"],
            'secret' => $wechat["AppSecret"],
            'response_type' => 'array'
        ];

        $app = Factory::officialAccount($config);
        $APIs = ["qrCode", "barCode", "scanQRCode"];
        $res = $app->jssdk->buildConfig($APIs, $debug = false, $beta = false, $json = true, [], config("api_url") . '/');
        $this->success("推荐人信息", json_decode($res, true));
    }

}
